// 云函数入口文件
const cloud = require('wx-server-sdk')

cloud.init({ env: cloud.DYNAMIC_CURRENT_ENV })

const db = cloud.database()
const _ = db.command

// 云函数入口函数
exports.main = async event => {
  const { OPENID: _openid } = cloud.getWXContext()
  if (!_openid) {
    throw new Error('no openid')
  }

  const { name, description, imgUrls, price, originalPrice, quota } = event
  if (!name || !description || !imgUrls || !price || !originalPrice || !quota) {
    throw new Error('missing parameters')
  }

  const createAt = new Date()
  const data = {
    _openid,
    name,
    description,
    imgUrls,
    price,
    originalPrice,
    quota,
    createAt,
    audit: { status: 0 },
  }

  await db.collection('promotion').add({ data })
}
